<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: yangsen
 * Date: 15/6/30
 * Time: 下午4:02
 */

ini_set('date.timezone','Asia/Shanghai');
require_once "./lib/WxPay.Api.php";
require_once './lib/WxPay.Notify.php';
require_once './lib/log.php';
require_once './lib/WxPay.JsApiPay.php';

$logHandler= new CLogFileHandler(APPPATH."logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class Pay extends MY_Controller {

    const STATUS_WAIT =1;
    const STATUS_GOAL=2;
    const STATUS_SENDED=3;
    const STATUS_FINISH=4;
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $dbconn = $this->load->database();
    }


    public function makeorder($goodsid)
    {
        $goodsinfo = $this->db->get_where('t_goods', array('id' => $goodsid), 0, 1);

        if ($goodsinfo) {
            $goodsinfo = $goodsinfo->result_array();
            $goodsinfo = $goodsinfo[0];
        }


        $orderid = $this->db->insert('t_order', array(
            'owner_openid' => $_SESSION['openid'],
            'goodsid' => $goodsid,
            'price' => $goodsinfo['price'],
            'ctime' => time(),
            'status' => Pay::STATUS_WAIT
        ));
        $data['id'] = $orderid;
        $n = $this->db->affected_rows();
        redirect('user/myorder', $data);
    }


    public function notify() {
        $msg = '不知道说什么';
        $this->load->library('PayNotifyCallBack');
        $notify = new PayNotifyCallBack();

       /* $ret = $notify->NotifyProcess(array(

            'result_code'=>'SUCCESS',
            'transaction_id'=>'00000011010',
            'out_trade_no'=>9999999
        ),$msg);
        echo $ret;
        echo $msg;*/
        $notify->Handle(false);

    }



    public function showmemoney() {
        $openid = $_SESSION['openid'];
        $data=array();
        if (empty($openid)) {
            redirect($this->getWechat()->wxOauthBase(base_url('/').'?redirect='.$_SERVER['REQUEST_URI']));
        }
        $flag_first = '';

        $orderid = $_GET['orderid'];
        if(!empty($orderid)) {

            $current = $this->db->get_where('t_order', array('id' => $orderid));
            $current = $current->result_array();
            $current = $current[0];
            $self_order = false;

            if ($current['owner_openid'] == $openid) {
                //自己的订单判断
                $self_ordr = true;
                $data['owner_nickname']=isset($_SESSION['userinfo']['realname'])?$_SESSION['userinfo']['realname']:$_SESSION['userinfo']['nickname'];
            } else {
                $data['owner_nickname'] = $this->db->select('nickname')->get_where('t_user',array('openid'=>$current['owner_openid']))->row(0)->nickname;
            }


            $data['logicgoodsid'] = $current['goodsid'];
            $goodsinfo = $this->db->select('title,picurl')->get_where('t_goods',array('id'=>$data['logicgoodsid']))->row(0);
            $data['logicgoodsname']=$goodsinfo->title;
            $data['logicgoodspic']=$goodsinfo->picurl;

            $data['logicorderid']=$orderid;

            $data['owner_openid']=$current['owner_openid'];
            $data['currmoney'] = 0;
            $is_nopayrecord = false;
            $data['needhowmuch'] = $current['price'];
            $pay_records = $this->db->select('sum(fee) as total_fee')->get_where('t_payrecord', array('orderid' => $orderid,'status'=>2), 0, 1);
            if (!empty($pay_records)) {
                $pay_records = $pay_records->result_array();
                $data['currmoney'] = $pay_records[0]['total_fee'] / 100;
                $data['needhowmuch'] = ($current['price'] - $pay_records[0]['total_fee']) / 100;

            } else {
                $is_nopayrecord = true;
            }

        }



        //或者需要附带的回掉URL的参数到attach

        //获取共享收货地址js函数参数
        $this->load->view('header');
        $this->load->view('showmemoney',$data);
    }




    public function payGateway() {
        $data['suc_msg']='充值成功了';
        $money = $this->input->post('money');
        $fee = $money*100;

        $logicgoodsid = $this->input->post('logicgoodsid');
        $goodsid = $this->input->post('goodsid');

        $goodstag = $this->input->post('goodstag');
        $outtransno = WxPayConfig::MCHID.date("YmdHis");

        //代表的商品ID和订单号和被赞助人openid
        $owner_openid = $this->input->post('owner_openid');
        $according_orderid = $this->input->post('according_orderid');



        //本次支付的虚拟商品和订单号和支付人openid和自定义msg
        $customer_msg=$this->input->post('customer_msg');
        $goodsname='1905钻石帮攒充值';

        $biz_flag = $this->input->post('biz_flag');
        if('createaccount'==$biz_flag) { //如果是开户业务,设置开户对应的参数
            $logicgoodsid=1;
            $goodsid=9998;
            $owner_openid = $_SESSION['openid'];
            $according_orderid=0;
            $customer_msg='开户费用10元';
            $data['suc_msg']='开户成功,设置个性化页面,让朋友们一起攒';
            $goodsname='1905钻石微信攒开户费';
            $fee=1;
        }


        $attachArray = array(
            'logicgoodsid'=>$logicgoodsid,
            'goodsid'=>$goodsid,
            'owner_openid'=>$owner_openid
        );

        $attach = base64_encode(json_encode($attachArray));


        function printf_info($data)
        {
            foreach($data as $key=>$value){
                echo "<font color='#00ff55;'>$key</font> : $value <br/>";
            }
        }

        //①、获取用户openid
        $tools = new JsApiPay();
        $openId = $_SESSION['openid'];
        if (empty($openId)) {
            $openId = $tools->GetOpenid();
        }

        //生成本地订单
        $lastOrderid = $this->db->insert('t_payrecord',array(
            'payer_openid'=>$openId,
            'owner_openid'=>$owner_openid,
            'orderid'=>$according_orderid,
            'payer_msg'=>$customer_msg,
            'goodsid'=>$goodsid,
            'logicgoodsid'=>$logicgoodsid,
            'fee'=>$fee,
            'ctime'=>time(),
            'status'=>1,
            'outtransno'=>$outtransno
        ));




        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($goodsname);
        $input->SetAttach($attach);
        $input->SetOut_trade_no($outtransno);
        $input->SetTotal_fee($fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("支持买钻金额测试");
        $input->SetNotify_url("http://weqing.juzili.net/zuan1905/pay/notify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        //echo 'ont color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printfnfo($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //echo 'jsapiParameter:<br/>';
        //echo $jsApiParameters;

        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $data['editAddress']=$editAddress;
        $data['jsApiParameters'] = $jsApiParameters;
        $this->load->view('jspay',$data);
    }
}